package com.ywgt.springcloud.controller;

import com.ywgt.springcloud.entities.CommonResult;
import com.ywgt.springcloud.entities.Payment;
import com.ywgt.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/payment/get/{id}")
    public CommonResult findById(@PathVariable("id") Long id){
        Payment result = paymentService.findById(id);
        if (result==null){
            log.info("查询为空");
            return new CommonResult(444,"查询不到id为"+id+"的用户",null);
        }else {
            log.info("查询成功"+result);
            return new CommonResult(200,"查询成功,server.Port:"+serverPort,result);
        }
    }

    @PostMapping("/payment/save")
    public CommonResult savePayment(@RequestBody Payment payment){
        int result = paymentService.savePayment(payment);
        if(result==1){
            log.info("插入成功，插入"+payment);
            return new CommonResult(200,"保存成功,serverPort:"+serverPort,result);
        }else {
            return new CommonResult(400,"保存失败",null);
        }
    }
    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("****element:"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String zipkin(){
        return "zipkin****"+serverPort;
    }
}
